﻿///<Summary>
/// Below block of code is very handy in investigating sharepoint logs for errors occured in SP2010 using PowerShell Commands
/// <Author>Rohit Singh - Senior Consultant</Author>
/// <Contributor>Girmaji Veda Prakash- Associate Consultant </Contributor>
///</Summary>
namespace Split.Core
{

    //C:\PS>Get-SPLogEvent -MinimumLevel "Warning"
    //This example returns all log entries equal to or more severe than Warning from the default log directory.

    //C:\PS>Get-SPLogEvent -StartTime "12/04/2007 17:00" -EndTime "12/04/2007 18:00"
    //This example returns error entries that occurred during a particular time range, which is culture-specific to the U
    //nited States.

    //C:\PS>Get-SPLogEvent | Where-Object {$_.Level -eq "Error" -and {$_.Area -eq "SharePoint Foundation "}
    //This example returns all error entries related to SharePoint Foundation.

    //C:\PS>Get-SPLogEvent -Directory "C:\Logs" | Where-Object {$_.Level -eq "Warning"}
    //This example returns all warning entries from log files in the C:\Logs directory.
    
    //C:\PS>Get-SPLogEvent -ContextKey @("UserName" ,"SiteName")
    //This example returns the contents of the most recent log file and adds the specified context key data.
       
    //C:\PS>Get-SPLogEvent -ContextKey @("Name") | %{$_.ToString() + "'t" + $_.Context["Name"]}
    //This example returns the contents of the log file and adds context data.


    #region Namespace reference
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.Management.Automation;
    using System.Management.Automation.Runspaces;
    using System.Text;
    using System.Diagnostics;
    using System.IO;
    using System.Linq;
    #endregion
    public class LogSearcher
    {
        /// <summary>
        /// This method will programmatically run the powershell script to retrieve error information from sharepoint logs
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        #region ExecuteScript
        

        private static IList ExecuteScript(string command)
        {
            RunspaceConfiguration config = RunspaceConfiguration.Create();
            PSSnapInException warning;            
            config.AddPSSnapIn("Microsoft.SharePoint.Powershell", out warning);
            if (warning != null)
            {
                throw warning;
            }            
            using (Runspace psRunspace = RunspaceFactory.CreateRunspace(config))
            {
                try
                {
                    psRunspace.Open();                    
                    using (Pipeline psPipe = psRunspace.CreatePipeline(command))
                    {
                        Collection<PSObject> psObjects = psPipe.Invoke();
                        if (psObjects.Count > 0)
                        {                            
                            Type psBaseObjectType = psObjects[0].BaseObject.GetType();
                            IList logEvents = (IList)Activator.CreateInstance((typeof(List<>).MakeGenericType(psBaseObjectType)));
                                foreach (PSObject psObjectItem in psObjects)
                                {                                    
                                    logEvents.Add(psObjectItem.BaseObject);
                                }
                                return logEvents;
                                                       
                        }
                        if (psPipe.Error != null && psPipe.Error.Count > 0)
                        {
                            StringBuilder pipelineError = new StringBuilder();
                            pipelineError.AppendFormat("Error calling Get-SpLogEvent");
                            foreach (object item in psPipe.Error.ReadToEnd())
                            {
                                pipelineError.AppendFormat("{0}\n", item.ToString());
                            }

                            throw new Exception(pipelineError.ToString());

                        }
                        psRunspace.Close();
                    }
                }
                catch
                {
                    throw;
                }
                return null;
            }
        }
        #endregion
        /// <summary>
        /// Method will take correlationid and timespan as parameters and return IList object with sharepoint log information
        /// </summary>
        /// <param name="correlationId"></param>
        /// <param name="timeSpan"></param>
        /// <returns></returns>
        #region GetLogFromCorrelation
        public static IList GetLogFromCorrelation(string correlationId, string timeSpan)
        {
            string command = "GET-SPLogEvent -starttime (get-date).addminutes(" + timeSpan + ") | where {$_.Correlation -eq '" + correlationId + "'}";
            return ExecuteScript(command);
        }

        public static IList GetLogs(DateTime startDate, DateTime endDate)
        {
            return GetLogs(startDate, endDate, string.Empty);
        }

        public static IList GetLogs(DateTime startDate, DateTime endDate, string level)
        {
            return null;
        }

        public static IList GetLogsForArea(DateTime startDate, DateTime endDate, string level, string area)
        {
            return null;
        }
        #endregion        
    }
}
